package crons

import (
	"chainserver/core/logs"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/robfig/cron"
	"go.uber.org/zap"
)

var c *cron.Cron

func Init() {
	c = cron.New()
	var err error
	for _, job := range jobs {
		err = c.AddFunc(job.spec, job.fun)
	}

	if err != nil {
		beego.Error("初始化定时任务失败")
		return
	}
	beego.Info("初始化定时任务成功")
	c.Run()
	return
}

type Spec struct {
	Second     string // 秒
	Minute     string // 分
	Hour       string // 小时
	DayOfMonth string // 每月第几天
	Month      string // 第几个月
	DayOfWeek  string // 每周第几天
}

type job struct {
	title string
	spec  string
	fun   func()
}

var jobs = make([]job, 0)

func RegisterJob(title string, spec Spec, fun func() (err error)) {
	specStr := fmt.Sprintf("%s %s %s %s %s %s", spec.Second, spec.Minute, spec.Hour, spec.DayOfMonth, spec.Month, spec.DayOfWeek)
	jobs = append(jobs, job{title: title, spec: specStr, fun: func() {
		var err error
		defer func() {
			if panicErr := recover(); panicErr != nil {
				logs.AliyunError("RegisterJobPanic", logs.GenErrInfo(panicErr))
			}
			if err != nil {
				logs.AliyunError("RegisterJobErr", logs.GenJobName(title), zap.Error(err))
			}
		}()
		err = fun()
	}})
	return
}
